﻿using System;
using System.ComponentModel;
using System.Threading;
using System.Windows;
using System.Windows.Navigation;
using DeepMixWorkflow;
using DeepmixRadioClient.Workflow;
using Microsoft.Phone.Marketplace;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using Microsoft.Xna.Framework.Media;
using MvvmBase.ViewModel;
using Telerik.Windows.Controls;
using GestureEventArgs = System.Windows.Input.GestureEventArgs;

namespace DeepmixRadioClient
{
    public partial class MainPage : IDispatcherOwner
    {
        private Logic _logic;

        public MainPage()
        {
            InitializeComponent();
            
            ApplicationBar.IsVisible = false;
#pragma warning disable 168 Because of app hub bug.
            var library = new MediaLibrary();
#pragma warning restore 168

            InteractionEffectManager.AllowedTypes.Add(typeof(RadDataBoundListBoxItem));

            if ((!StorageContainer.IsInitialized.Exists
                &&
                !StorageContainer.ServerAddress.Exists)
                || StorageContainer.UpdateVersion.Value < 3
                )
            {
                StorageContainer.UpdateVersion.Value = 3;
                StorageContainer.ServerAddress.Value =
                    Thread.CurrentThread.CurrentCulture.Name.ToUpper() == "ru-RU".ToUpper()
                    //îñòàâëÿåì òàê, ñêîðî àäðåñ áóäåò îäèí - íåò ñìûñëà ýòî ïåðåäåëûâàòü
                        ? @"http://217.23.7.117:8128"
                        : "http://69.163.134.109:8128";

                StorageContainer.IsInitialized.Value = true;

                WelcomeStreen.Visibility = Visibility.Visible;
                WelcomeTxt.Text = AppResources.WeccomeText;
            }


#if BETA
            var applicationBarMenuItem = new ApplicationBarMenuItem() {Text = "Log"};
            applicationBarMenuItem.Click += showLog_Clicked;
            ApplicationBar.MenuItems.Add(applicationBarMenuItem);
#endif

            PlayPauseButton.Text = AppResources.PlayButton;
            StopButton.Text = AppResources.StopButton;
            PrevButton.Text = AppResources.BackButton;
            NextButton.Text = AppResources.NextButton;
            ((ApplicationBarMenuItem)ApplicationBar.MenuItems[0]).Text = AppResources.Refresh;
            ((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).Text = AppResources.Settings;
            ((ApplicationBarMenuItem)ApplicationBar.MenuItems[2]).Text = AppResources.About;
            var licenseInformation = new LicenseInformation();
            if (licenseInformation.IsTrial())
            {
                var menuItem = new ApplicationBarMenuItem(AppResources.Donate) { IsEnabled = true };
                menuItem.Click += donate_Clicked;
                ApplicationBar.MenuItems.Add(menuItem);
            }
            Loaded += OnLoaded;
        }

        private void donate_Clicked(object sender, EventArgs eventArgs)
        {

            if (MessageBox.Show(AppResources.DonateWarning) == MessageBoxResult.OK)
            {
                var mpTask = new MarketplaceDetailTask();
                try
                {
                    mpTask.Show();
                }
                catch
                {
                    //такое бывает при переключении, не помню какое исключение
                }
            }
        }

        private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
        {
            InitViewModel();
        }

        #region Buttons

        private ApplicationBarIconButton PrevButton
        {
            get { return (ApplicationBarIconButton)ApplicationBar.Buttons[0]; }
        }

        private ApplicationBarIconButton PlayPauseButton
        {
            get { return (ApplicationBarIconButton)ApplicationBar.Buttons[1]; }
        }

        private ApplicationBarIconButton StopButton
        {
            get { return (ApplicationBarIconButton)ApplicationBar.Buttons[2]; }
        }

        private ApplicationBarIconButton NextButton
        {
            get { return (ApplicationBarIconButton)ApplicationBar.Buttons[3]; }
        }

        #endregion

        protected override void OnBackKeyPress(CancelEventArgs e)
        {
            if (AboutBorder.Visibility == Visibility.Visible)
            {
                AboutBorder.Visibility = Visibility.Collapsed;
                e.Cancel = true;
            }
        }

#if BETA
        private void showLog_Clicked(object sender, EventArgs e)
        {
            welcomeStreen.Visibility = Visibility.Visible;
            welcomeTxt.Text = CommonHelper.SendLog();
        }
#endif

        private void InitViewModel()
        {
            DataContext =
                _logic =
                new Logic(this, new InternalNavigator(((App)Application.Current).RootFrame), ProgramLst.BringIntoView,
                          SelLst.BringIntoView);

            _logic.IsPrevEnabledChanged += UpdatePrevButton;
            _logic.IsNextEnabledChanged += UpdateNextButton;
            _logic.IsStopEnabledChanged += UpdateStopButton;
            _logic.IsPlayOrPauseChanged += UpdatePlayButton;
            _logic.LockPlayAndSkip += LockPlayAndSkip;
            _logic.TimeLite += LogicOnTimeLite;
            UpdateAll();
            ApplicationBar.IsVisible = true;
        }

        private void LogicOnTimeLite(object sender, EventArgs eventArgs)
        {
            TimeLite.Begin();
        }

        private void UpdateAll()
        {
            _logic.SelectPlayingTrack();
            UpdatePrevButton();
            UpdateNextButton();
            UpdateStopButton();
            UpdatePlayButton();
        }

        #region Buttons

        private void LockPlayAndSkip()
        {
            PrevButton.IsEnabled = false;
            NextButton.IsEnabled = false;
            PlayPauseButton.IsEnabled = false;
        }

        private void UpdatePlayButton()
        {
            bool? playOrPause = _logic.IsPlayOrPause;
            if (playOrPause == null)
            {
                PlayPauseButton.IconUri = new Uri(@"/icons/appbar.transport.play.rest.png", UriKind.RelativeOrAbsolute);
                PlayPauseButton.IsEnabled = false;
                return;
            }
            if ((bool)playOrPause)
            {
                PlayPauseButton.IconUri = new Uri(@"/icons/appbar.transport.play.rest.png", UriKind.RelativeOrAbsolute);
                PlayPauseButton.IsEnabled = true;
            }
            else
            {
                PlayPauseButton.IconUri = new Uri(@"/icons/appbar.transport.pause.rest.png", UriKind.RelativeOrAbsolute);
                PlayPauseButton.IsEnabled = true;
            }
        }

        private void UpdateStopButton()
        {
            StopButton.IsEnabled = _logic.IsStopEnabled;
        }

        private void UpdateNextButton()
        {
            NextButton.IsEnabled = _logic.IsNextEnabled;
        }

        #endregion

        #region Button Actions

        private void goBack_Clicked(object sender, EventArgs e)
        {
            _logic.GoPrev();
        }

        private void goNext_Clicked(object sender, EventArgs e)
        {
            _logic.GoNext();
        }

        private void stop_Clicked(object sender, EventArgs e)
        {
            _logic.Stop();
        }

        private void play_Clicked(object sender, EventArgs e)
        {
            _logic.PlayClicked();
        }

        #endregion

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (_logic != null)
            {
                UpdateAll();
            }
        }

        private void UpdatePrevButton()
        {
            PrevButton.IsEnabled = _logic.IsPrevEnabled;
        }

        private void closeaboutBorder_Clicked(object sender, GestureEventArgs e)
        {
            AboutBorder.Visibility = Visibility.Collapsed;
        }

        private void showAbout_Clicked(object sender, EventArgs e)
        {
            AboutBorder.Visibility = Visibility.Visible;
            AboutTxt.Text = AppResources.AboutText;
        }

        private void update_Clicked(object sender, EventArgs e)
        {
            _logic.UpdateAll();
        }

        private void goDeepMix_Clicked(object sender, RoutedEventArgs e)
        {
            var task = new WebBrowserTask { Uri = new Uri(AppResources.DeeMixSite) };
            task.Show();
        }

        private void close_Welcome(object sender, GestureEventArgs e)
        {
            CloseWellcome();
        }

        private void CloseWellcome()
        {
            if (_logic.IsBusy || _logic.IsSmallBusy)
            {
                ((App)Application.Current).RootFrame.IsEnabled = false;
            }

            WelcomeStreen.Visibility = Visibility.Collapsed;

        }

        private void showSettings_Clicked(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Settings.xaml", UriKind.RelativeOrAbsolute));
        }

        public void ExectuteIfCan(Action action)
        {
            if (Dispatcher.CheckAccess())
            {
                action();
            }
            else
            {
                Dispatcher.BeginInvoke(action);
            }
        }

        private void back_Pressed(object sender, CancelEventArgs e)
        {
            if (WelcomeStreen.Visibility == Visibility.Visible)
            {
                CloseWellcome();
                e.Cancel = true;
            }
        }
    }
}